package component

import (
	"cke.io/ckectl/app/apis/v1alpha1"
	"cke.io/ckectl/app/constants"
	"fmt"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	utilsexec "k8s.io/utils/exec"
	"os"
	"os/exec"
)

//extract script into sub dir
func ExtractScript(containerName, imageName string, component v1alpha1.CkeComponent) error {
	dockerRunTime, err := NewContainerRuntime(utilsexec.New())
	utilruntime.HandleError(err)

	if exist, err := dockerRunTime.ImageExists(imageName); err != nil || !exist {
		err = dockerRunTime.PullImage(imageName)
		if err != nil {
			return fmt.Errorf("fail pull images: %s, err: %s", imageName, err.Error())
		}
	}

	//清空对应插件子目录
	_ = os.RemoveAll(CkectlScriptPath + "/" + component.Name)

	err = dockerRunTime.RemoveContainers([]string{containerName})
	dockerArgs := []string{
		"run",
		"--rm",
		"-v", CkectlScriptPath + ":" + CkectlScriptPath,
		"--name", containerName,
	}

	// #nosec
	var running = exec.Command("docker", append(dockerArgs, imageName, "/bin/cp", "-rf", "/template", CkectlScriptPath+"/"+component.Name)...)

	output, err := running.CombinedOutput()
	fmt.Printf("%s\n", string(output))
	return err
}

func GetImageName(cluster v1alpha1.CkeCluster, component v1alpha1.CkeComponent) string {
	return GetImage(cluster.Spec.Registry.Domain, cluster.Spec.Registry.Port, CkeComponentScriptImageRepo+component.Name,
		component.Spec.ImageTag, cluster.Spec.ClusterParameters.ImageManifestEnabled)
}

func GetImageNameFromStatus(cluster v1alpha1.CkeCluster, component v1alpha1.CkeComponent) string {
	return GetImage(cluster.Spec.Registry.Domain, cluster.Spec.Registry.Port, CkeComponentScriptImageRepo+component.Name,
		component.Status.ImageTag, cluster.Spec.ClusterParameters.ImageManifestEnabled)
}

func GetImage(registry string, port int, name, tag string, disableArchTag bool) string {
	var head, body, end = GetRegistry(registry, port), name, tag

	// if enable archtag, add arch information for image. such as xxx-amd64
	if !disableArchTag {
		body = fmt.Sprintf("%s-%s", body, constants.ARCH)
	}

	return fmt.Sprintf("%s/%s:%s", head, body, end)
}

func GetRegistry(registry string, port int) string {
	// if has port, config registry with port as xxxx:xxxx
	if port > 0 {
		return fmt.Sprintf("%s:%d", registry, port)
	}

	return registry
}
